<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search as IconSearch, Calendar as IconCalendar, Plus as IconPlus, View as IconView } from '@element-plus/icons-vue'
import inboundApi from '@/api/inbound'
import itemApi from '@/api/item'
import warehouseApi from '@/api/warehouse'
import type { InboundRecordInfo, InboundRecordListParams, CreateInboundRecordParams } from '@/api/inbound'
import type { ItemInfo } from '@/api/item'
import type { WarehouseInfo } from '@/api/warehouse'

const tableData = ref<InboundRecordInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const searchParams = ref<InboundRecordListParams>({
  page: currentPage.value,
  pageSize: pageSize.value,
  itemId: undefined,
  warehouseId: undefined,
  startTime: undefined,
  endTime: undefined,
})

const itemOptions = ref<ItemInfo[]>([])
const warehouseOptions = ref<WarehouseInfo[]>([])
const dateRange = ref<[Date, Date] | null>(null)

// 创建入库记录相关数据
const createDialogVisible = ref(false)
const createFormRef = ref()
const createForm = ref<CreateInboundRecordParams>({
  itemId: undefined as any,
  warehouseId: undefined as any,
  quantity: 0,
  unitPrice: 0,
  supplier: '',
  notes: '',
})

// 查看入库记录详情相关数据
const detailDialogVisible = ref(false)
const inboundRecordDetail = ref<InboundRecordInfo | null>(null)
const detailLoading = ref(false)

// 创建表单验证规则
const createFormRules = {
  itemId: [
    { required: true, message: '请选择物品', trigger: 'change' }
  ],
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
           callback(new Error('请输入入库数量'))
        } else if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效的数字'))
        } else if (value <= 0) { // 数量必须大于0
          callback(new Error('数量必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  unitPrice: [
    { required: true, message: '请输入物品单价', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
           callback(new Error('请输入物品单价'))
        } else if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效的数字'))
        } else if (value < 0) { // 单价不能小于0
          callback(new Error('单价不能小于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  supplier: [
    { required: true, message: '请输入供应商', trigger: 'blur' },
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ],
  notes: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 计算总金额
const calculatedTotalAmount = computed(() => {
  return (createForm.value.quantity || 0) * (createForm.value.unitPrice || 0);
});

// 获取入库记录列表
const getInboundRecordList = async () => {
  loading.value = true
  try {
    const params: InboundRecordListParams = {
      ...searchParams.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    }
     // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      // 确保日期是 UTC 格式或后端需要的格式
      params.startTime = dateRange.value[0]?.toISOString() || undefined;
      params.endTime = dateRange.value[1]?.toISOString() || undefined;
    } else {
      params.startTime = undefined;
      params.endTime = undefined;
    }

    const res = await inboundApi.getInboundRecordList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取入库记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取物品选项
const getItemOptions = async () => {
  try {
    const res = await itemApi.getItemList({ page: 1, pageSize: 1000 })
    itemOptions.value = res.data.list
  } catch (error) {
    // 忽略错误，不影响主流程
  }
}

// 获取仓库选项
const getWarehouseOptions = async () => {
  try {
    const res = await warehouseApi.getWarehouseList({ pageNum: 1, pageSize: 1000 })
    warehouseOptions.value = res.data.list
  } catch (error) {
    // 忽略错误，不影响主流程
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getInboundRecordList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getInboundRecordList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getInboundRecordList()
}

// 处理日期范围变化
const handleDateChange = (val: [Date, Date] | null) => {
  dateRange.value = val;
}

// 打开创建入库记录对话框
const handleCreate = () => {
  createDialogVisible.value = true
  // 重置表单数据
  createForm.value = {
    itemId: undefined as any,
    warehouseId: undefined as any,
    quantity: 0,
    unitPrice: 0,
    supplier: '',
    notes: '',
  };
  // 重置表单验证状态
  createFormRef.value?.resetFields();
}

// 提交创建入库记录表单
const handleSubmit = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await inboundApi.createInboundRecord(createForm.value)
        ElMessage.success('创建入库记录成功')
        createDialogVisible.value = false
        getInboundRecordList() // 刷新列表
      } catch (error) {
        ElMessage.error('创建入库记录失败')
      }
    }
  })
}

// 取消创建
const handleCancel = () => {
  createDialogVisible.value = false
  createFormRef.value?.resetFields()
}

// 查看入库记录详情
const handleViewDetail = async (row: InboundRecordInfo) => {
  detailLoading.value = true
  try {
    const res = await inboundApi.getInboundRecordById(row.inboundId)
    inboundRecordDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取入库记录详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  inboundRecordDetail.value = null
}

onMounted(() => {
  getItemOptions()
  getWarehouseOptions()
  getInboundRecordList()
})
</script>

<template>
  <div class="inbound-record-list-container">
    <div class="search-bar">
      <el-select
        v-model="searchParams.itemId"
        placeholder="请选择物品"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="item in itemOptions"
          :key="item.itemId"
          :label="item.itemName"
          :value="item.itemId"
        />
      </el-select>

      <el-select
        v-model="searchParams.warehouseId"
        placeholder="请选择仓库"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="warehouse in warehouseOptions"
          :key="warehouse.warehouseId"
          :label="warehouse.warehouseName"
          :value="warehouse.warehouseId"
        />
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :prefix-icon="IconCalendar"
        @change="handleDateChange"
      />

      <el-button type="primary" :icon="IconSearch" @click="handleSearch">搜索</el-button>
      <el-button type="success" :icon="IconPlus" @click="handleCreate">新增入库</el-button>
    </div>

    <el-table :data="tableData" border v-loading="loading" style="width: 100%" class="inbound-record-table">
      <el-table-column prop="inboundId" label="记录ID" width="80" />
      <el-table-column label="物品" width="150">
        <template #default="{ row }">
          {{ row.item?.itemName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="仓库" width="150">
        <template #default="{ row }">
          {{ row.warehouse?.warehouseName || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="80" />
      <el-table-column prop="unitPrice" label="单价" width="100" />
      <el-table-column prop="totalAmount" label="总金额" width="120" />
      <el-table-column prop="supplier" label="供应商" width="150" show-overflow-tooltip />
      <el-table-column label="操作员" width="120">
         <template #default="{ row }">
          {{ row.operator?.realName || row.operator?.username || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="inboundTime" label="入库时间" width="180" />
      <el-table-column prop="notes" label="备注" min-width="200" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column label="操作" width="80" fixed="right">
         <template #default="{ row }">
            <el-button
              type="primary"
              :icon="IconView"
              circle
              @click="handleViewDetail(row)"
            />
         </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="!total"
      />
    </div>
  </div>

  <!-- 创建入库记录对话框 -->
  <el-dialog
    v-model="createDialogVisible"
    title="新增入库记录"
    width="500px"
    @close="handleCancel"
  >
    <el-form
      ref="createFormRef"
      :model="createForm"
      :rules="createFormRules"
      label-width="100px"
    >
      <el-form-item label="物品" prop="itemId">
        <el-select v-model="createForm.itemId" placeholder="请选择物品">
          <el-option
            v-for="item in itemOptions"
            :key="item.itemId"
            :label="item.itemName"
            :value="item.itemId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="createForm.warehouseId" placeholder="请选择仓库">
          <el-option
            v-for="warehouse in warehouseOptions"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input-number
          v-model="createForm.quantity"
          :min="1"
          :controls="false"
          placeholder="请输入入库数量"
        />
      </el-form-item>
      <el-form-item label="单价" prop="unitPrice">
        <el-input-number
          v-model="createForm.unitPrice"
          :min="0"
          :controls="false"
          :precision="2"
          placeholder="请输入物品单价"
        />
      </el-form-item>
      <el-form-item label="总金额">
         {{ calculatedTotalAmount.toFixed(2) }}
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input v-model="createForm.supplier" placeholder="请输入供应商名称" />
      </el-form-item>
       <el-form-item label="备注" prop="notes">
        <el-input
          v-model="createForm.notes"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定入库</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 入库记录详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="入库记录详情"
    width="600px"
    @close="handleCloseDetail"
  >
    <div v-loading="detailLoading">
      <template v-if="inboundRecordDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">
            {{ inboundRecordDetail.inboundId }}
          </el-descriptions-item>
          <el-descriptions-item label="物品">
            {{ inboundRecordDetail.item?.itemName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="仓库">
            {{ inboundRecordDetail.warehouse?.warehouseName || '-' }}
          </el-descriptions-item>
           <el-descriptions-item label="数量">
            {{ inboundRecordDetail.quantity }}
          </el-descriptions-item>
          <el-descriptions-item label="单价">
            {{ inboundRecordDetail.unitPrice.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            {{ inboundRecordDetail.totalAmount.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商">
            {{ inboundRecordDetail.supplier || '-' }}
          </el-descriptions-item>
           <el-descriptions-item label="操作员">
            {{ inboundRecordDetail.operator?.realName || inboundRecordDetail.operator?.username || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="入库时间">
            {{ inboundRecordDetail.inboundTime }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ inboundRecordDetail.notes || '-' }}
          </el-descriptions-item>
           <el-descriptions-item label="创建时间">
            {{ inboundRecordDetail.createdAt }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </div>
  </el-dialog>
</template>

<style scoped>
.inbound-record-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-select {
  width: 180px;
}

.inbound-record-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-select,
.el-input-number {
  width: 100%;
}

/* 可以添加更多样式来优化表格和表单的布局和外观 */
</style> 